'''
该模块包含框架类和由它们组成的窗口类
框架主要使用网格grid布局，组成窗口时采用place布局
'''

from tkinter import *
from tkinter import ttk
import tkinter.messagebox
import random
import customTool 
import sqliteTool
import time

class LoginFrame(Frame):
    """登录框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master)       
        self.highlightthickness=2

        self.input_name=StringVar(master=master)
        self.input_password=StringVar(master=master)
        #主文本框
        self.main_label =Label(
            master=self,
            text="用户登录",
            bg="#191981",fg="#000000",
            font=('Times',40,'bold italic')
            )
        #用户名和密码文本框
        self.name_label =Label(
            master=self,
            text="用户名",
            font=('Times',20,'bold italic')
            )
        self.password_label =Label(
            master=self,
            text="用户密码",
            font=('Times',20,'bold italic')
            )
        #用户名和密码输入框
        self.name_entry =Entry(
            master=self,
            textvariable=self.input_name,
            font=('Times',20,'bold italic')
            )
        self.password_entry =Entry(
            master=self,
            textvariable=self.input_password,
            font=('Times',20,'bold italic')
            )
        #登录和注册按钮
        self.login_button=Button(
            master=self,
            text='登录(进入下一界面)',
            command=self.login_event,
            cursor='plus',
            relief="ridge"
            )
        self.register_button=Button(
            master=self,
            text='注册',
            command=self.register_event,
            cursor='plus',
            relief="ridge"
            )
        #调用布局函数，按一定规律放置上述组件
        self.grid_all()

    def login_event(self):
        """登录函数"""
        if (len(str(self.name_entry.get()))+len(str(self.password_entry.get())))<=1:
             tkinter.messagebox.showinfo("登录失败","请输入用户名和密码")
        else:
            user_id=sqliteTool.get_user_id(self.input_name.get(),self.input_password.get())
            if(len(user_id)==0):
                tkinter.messagebox.showinfo("登录失败","用户名或密码错误")
            else:
                user_id=int(user_id)
                user_category=sqliteTool.get_user_category(user_id)
                tkinter.messagebox.showinfo("登录成功","你好, {0} {1}".format(user_category,self.input_name.get()))
                new_window=None
                new_new_window=None
                new_new_new_window=None
                if user_category=="主管":
                    new_window=DishManagerWindow()                    
                    new_new_window=UserManagerWindow()
                    new_new_new_window=OrderViewWindow()
                elif user_category=="顾客":
                    new_window=OrderWindow()
                elif user_category=="管理员":
                    new_window=DishManagerWindow()
                    new_new_window=UserManagerWindow(root=FALSE)
                    new_new_new_window=OrderViewWindow()
                elif user_category=="厨师" :
                    new_window=CookWindow(str(user_id))
                elif user_category=="采购员":
                    new_window=OrderViewWindow()
                    new_new_window=DishViewWindow()
                elif user_category=="服务员":
                    new_new_window=ServerWindow(user_id)
                if(new_window):
                    new_window.title(new_window.title()+"(当前身份:"+user_category+")")
                if(new_new_window):
                    new_new_window.title(new_new_window.title()+"(当前身份:"+user_category+")")
                if(new_new_new_window):
                    new_new_new_window.title(new_new_new_window.title()+"(当前身份:"+user_category+")")

    def register_event(self):
        """注册函数"""
        new_window=RegisterWindow()

    def grid_all(self):
        """布局函数"""
        self.main_label.grid(row=0,column=0,columnspan=3)   
        self.name_label.grid(row=1,column=0)
        self.password_label.grid(row=2,column=0)
        self.name_entry.grid(row=1,column=1,columnspan=2)
        self.password_entry.grid(row=2,column=1,columnspan=2)
        self.login_button.grid(row=3,column=0)
        self.register_button.grid(row=3,column=2)

class RegisterFrame(Frame):
    """注册框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master)       
        self.highlightthickness=2

        self.input_name=StringVar(master=master)
        self.input_password=StringVar(master=master)
        self.user_type=['选择身份','顾客','厨师','服务员','采购员']
        #self.user_type=['CUSTOMER','MANAGER','COOK','SERVER','BUYER']
        
        #主文本框
        self.main_label =Label(
            master=self,
            text="用户注册",
            bg="#191981",fg="#000000",
            font=('Times',40,'bold italic')
            )
        #用户名和密码文本框
        self.name_label =Label(
            master=self,
            text="填写用户名",
            font=('Times',20,'bold italic')
            )
        self.password_label =Label(
            master=self,
            text="填写密码",
            font=('Times',20,'bold italic')
            )

        #用户类型筛选下拉列表
        self.combobox_type=ttk.Combobox(
            master=self,
            value= self.user_type,
            )
        self.combobox_type.current(0)

        #用户名和密码输入框
        self.name_entry =Entry(
            master=self,
            textvariable=self.input_name,
            font=('Times',20,'bold italic')
            )
        self.password_entry =Entry(
            master=self,
            textvariable=self.input_password,
            font=('Times',20,'bold italic')
            )

        #电话提示和输入框
        self.phone_label =Label(
            master=self,
            text="填写电话号码",
            font=('Times',20,'bold italic')
            )
        self.phone_entry =Entry(
            master=self,
            font=('Times',20,'bold italic')
            )

        #登录和注册按钮
        self.register_button=Button(
            master=self,
            text='注册',
            command=self.register_event,
            cursor='plus',
            relief="ridge"
            )
        #调用布局函数，按一定规律放置上述组件
        self.grid_all()

    def register_event(self):
        """注册函数"""
        if sqliteTool.get_user_contain("NAME",self.name_entry.get()):
            tkinter.messagebox.showinfo("注册失败","该用户名已经被注册了")
        else:           
            sqliteTool.add_user(
                sqliteTool.user_next_id(),
                self.name_entry.get(),
                self.password_entry.get(),
                self.combobox_type.get(),
                self.phone_entry.get(),
                time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                )
            tkinter.messagebox.showinfo("注册成功","欢迎你!"+self.name_entry.get())
            self.master.destroy()

    def grid_all(self):
        """布局函数"""
        self.main_label.grid(row=0,column=0,columnspan=3)  
        
        self.name_label.grid(row=1,column=0)       
        self.name_entry.grid(row=1,column=1,columnspan=2)

        self.password_label.grid(row=2,column=0)
        self.password_entry.grid(row=2,column=1,columnspan=2)

        self.phone_label.grid(row=3,column=0)
        self.phone_entry.grid(row=3,column=1)

        self.combobox_type.grid(row=4,column=0)
        self.register_button.grid(row=4,column=1)      

class CloseFrame(Frame):
    """退出框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master)       
        self.highlightthickness=1
        #退出按钮
        self.button_close=Button(
            master=self,
            text='关闭窗口',
            command=master.destroy,
            cursor='plus',
            relief="ridge"
        )
        #布局组件
        self.grid_all()

    def grid_all(self):
        """布局函数"""
        self.button_close.grid(row=0,column=0)   

class DishViewFrame(Frame):
    """餐品数据展示框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master)    
        #菜品类型
        self.list_dishes_type=['筛选菜品','肉类','蔬菜','米面','水果','速食类','甜点','饮料','其它']
        
        #菜品数据表中，各列属性为['ID','NAME','TYPE','PRICE','MONEYCOST','TIMECOST','STAR']
        #中文菜品表头
        self.list_dishes_head=['序号','名称','类型','价格','平均制作成本','平均制作时间','评价']
        
        #界面控件:
        #菜品类型筛选下拉列表
        self.combobox_type=ttk.Combobox(
            master=self,
            value= self.list_dishes_type
            )
        #绑定方法，值改变时触发
        self.combobox_type.bind("<<ComboboxSelected>>",self.combobox_type_event)
        self.combobox_type.current(0)

        #菜品表格树
        self.treeview_order=ttk.Treeview(
            master=self,
            columns=['序号','类型','价格','平均制作成本','平均制作时间','评价'],
            )
        #添加并设置各列
        self.treeview_order.heading('#0',text= "名称") 
        self.treeview_order.column('#0',width=100) 
        for head in self.list_dishes_head:
            if head=='名称':
                continue
            self.treeview_order.heading(column=head,text=head,anchor=CENTER)
            self.treeview_order.column(column=head,width=80,anchor=CENTER)  
        #调用函数添加树结点数据
        self.add_node(0)

        #菜品表格树滚动条
        self.scroll_order=ttk.Scrollbar(
            master=self,
            orient='vertical'
            )
        #双向绑定菜品表格的位置和滚动条位置
        self.treeview_order.configure(yscrollcommand=self.scroll_order.set)
        self.scroll_order.config(command=self.treeview_order.yview)
        
        #刷新菜品按钮
        self.button_update=Button(
            master=self,
            text='刷新',
            command=self.add_node,
            cursor='plus',
            relief="ridge"
            )

        #调用布局函数
        self.grid_all()

    def combobox_type_event(self,event):
        """菜品类型的下拉列表的事件处理方法"""    
        for i in range(0,len(self.list_dishes_type)):
            if(self.combobox_type.get()==self.list_dishes_type[i]):
                self.add_node(i)

    def add_node(self,index=0):      
        """根据输入值添加对应的菜品数据到表格，值为0时添加所有"""
        #删除所有菜品结点
        for child in self.treeview_order.get_children():
            self.treeview_order.delete(child)
        #获取数据库中菜品表
        dishes_data=sqliteTool.get_dish()
        #根据菜品类型添加节点 ['餐品类型','肉类','蔬菜','米面','水果','速食类','甜点','饮料','其它']
        self.node_meat=self.treeview_order.insert('',END,text=self.list_dishes_type[1],open=True)
        self.node_vegetable=self.treeview_order.insert('',END,text=self.list_dishes_type[2],open=True)
        self.node_fruit=self.treeview_order.insert('',END,text=self.list_dishes_type[3],open=True)
        self.node_rice=self.treeview_order.insert('',END,text=self.list_dishes_type[4],open=True)
        self.node_quick=self.treeview_order.insert('',END,text=self.list_dishes_type[5],open=True)
        self.node_dessert=self.treeview_order.insert('',END,text=self.list_dishes_type[6],open=True)
        self.node_drink=self.treeview_order.insert('',END,text=self.list_dishes_type[7],open=True)
        self.node_other=self.treeview_order.insert('',END,text=self.list_dishes_type[8],open=True)
        
        #表格树中各列表头:
        #['序号','名称','类型','价格','平均制作成本','平均制作时间','评价']
        #数据表中各列属性:
        #['ID','NAME','TYPE','PRICE','MONEYCOST','TIMECOST','STAR']

        #根据index添加子节点
        for row in dishes_data:
                #print(row)
                if(row[2]==self.list_dishes_type[1] and (index==0 or index==1)):
                    self.treeview_order.insert(self.node_meat,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[2]and (index==0 or index==2)):
                    self.treeview_order.insert(self.node_vegetable,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[3]and (index==0 or index==3)):
                    self.treeview_order.insert(self.node_fruit,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[4]and (index==0 or index==4)):
                    self.treeview_order.insert(self.node_rice,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[5]and (index==0 or index==5)):
                    self.treeview_order.insert(self.node_quick,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[6]and (index==0 or index==6)):
                    self.treeview_order.insert(self.node_dessert,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[7]and (index==0 or index==7)):
                    self.treeview_order.insert(self.node_drink,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))
                if(row[2]==self.list_dishes_type[8]and (index==0 or index==8)):
                    self.treeview_order.insert(self.node_other,END,text=row[1],value=(row[0],row[2],row[3],row[4],row[5],row[6]))

    def grid_all(self):
        """布局函数"""
        self.combobox_type.grid(row=0,column=0)
        self.button_update.grid(row=0,column=1)
        self.treeview_order.grid(row=1,column=0,columnspan=4)
        self.scroll_order.grid(row=1,column=4,sticky='SN')

class AddDishFrame(Frame):
    """添加菜品框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master)       
        #菜品类别
        self.list_dishes_type=['肉类','蔬菜','米面','水果','速食类','甜点','饮料','其它']   
        #添加新菜品相关组件 
        #需要输入的数据有:['ID','NAME','TYPE','PRICE','MONEYCOST','TIMECOST','STAR']   
        #文本框，提示输入菜品序号
        self.label_id=Label(
            master=self,
            text='菜品序号',
            font=('Times',10,'bold italic')
            )
        #输入框,输入菜品序号
        self.entry_input_id=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，提示输入菜品名称
        self.label_name=Label(
            master=self,
            text='菜品名称',
            font=('Times',10,'bold italic')
            )
        #输入框,输入菜品名称
        self.entry_input_name=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，提示输入菜品类型
        self.label_type=Label(
            master=self,
            text='菜品类型',
            font=('Times',10,'bold italic')
            )
        #下拉列表，输入菜品类型
        self.combobox_input_type=ttk.Combobox(
            master = self,
            value = self.list_dishes_type
            )
        self.combobox_input_type.current(0)

        #文本框，提示输入菜品价格
        self.label_price=Label(
            master=self,
            text='菜品价格',
            font=('Times',10,'bold italic')
            )
        #输入框,输入菜品价格
        self.entry_input_price=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，提示输入菜品经济成本
        self.label_moneycost=Label(
            master=self,
            text='菜品经济成本',
            font=('Times',10,'bold italic')
            )
        #输入框,输入菜品经济成本
        self.entry_input_moneycost=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，提示输入菜品时间成本
        self.label_timecost=Label(
            master=self,
            text='菜品时间成本',
            font=('Times',10,'bold italic')
            )
        #输入框,输入菜品时间成本
        self.entry_input_timecost=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )
                 
        #按钮，按下后根据输入添加菜品
        self.button_add=Button(
            master=self,
            text='添加菜品',
            command=self.add_event,
            cursor='plus',
            relief="ridge"
            )     
        #按钮，按下后根据输入修改菜品
        self.button_update=Button(
            master=self,
            text='修改菜品',
            command=self.update_event,
            cursor='plus',
            relief="ridge"
            )         
        #按钮，按下后根据ID删除菜品
        self.button_remove=Button(
            master=self,
            text='删除菜品',
            command=self.remove_event,
            cursor='plus',
            relief="ridge"
            )

        self.grid_all()

    def add_event(self):
        """根据输入数据添加菜品"""
        sqliteTool.add_dish(
            id=self.entry_input_id.get(),
            name=self.entry_input_name.get(),
            type=self.combobox_input_type.get(),
            price=self.entry_input_price.get(),
            money_cost=self.entry_input_moneycost.get(),
            time_cost=self.entry_input_timecost.get()
            )      

    def update_event(self):
        """根据输入的序号修改菜品"""
        sqliteTool.update_dish(
            id=self.entry_input_id.get(),
            name=self.entry_input_name.get(),
            type=self.combobox_input_type.get(),
            price=self.entry_input_price.get(),
            money_cost=self.entry_input_moneycost.get(),
            time_cost=self.entry_input_timecost.get()
            )      

    def remove_event(self):
        """根据输入的序号删除菜品"""
        sqliteTool.remove_dish(
            id=self.entry_input_id.get()
            )

    def grid_all(self):
        """布局函数"""
        self.label_type.grid(row=0,column=0)
        self.label_id.grid(row=0,column=1)
        self.label_name.grid(row=0,column=2)
        self.label_price.grid(row=2,column=0)
        self.label_moneycost.grid(row=2,column=1)
        self.label_timecost.grid(row=2,column=2)

        self.combobox_input_type.grid(row=1,column=0,padx='10px') 
        self.entry_input_id.grid(row=1,column=1)
        self.entry_input_name.grid(row=1,column=2)
        self.entry_input_price.grid(row=3,column=0)
        self.entry_input_moneycost.grid(row=3,column=1)
        self.entry_input_timecost.grid(row=3,column=2)
        
        self.button_add.grid(row=1,column=3,rowspan=1,padx='20px',sticky=NS)
        self.button_remove.grid(row=2,column=3,rowspan=1,padx='20px',sticky=NS)
        self.button_update.grid(row=3,column=3,rowspan=1,padx='20px',sticky=NS)

class OrderDishFrame(Frame):
    """下订单菜品框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master)       
        #单样菜品订单字典
        self.dict_order={"ID":"","Name":"","Price":"","Amount":""}
        #汇总订单列表
        self.list_order=[]
        
        #文本框，提示输入菜品序号
        self.label_name=Label(
            master=self,
            text='菜品名称',
            font=('Times',10,'bold italic')
            )
        #输入框,输入菜品序号
        self.entry_input_name=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，提示输入订购数量
        self.label_amount=Label(
            master=self,
            text='订购数量',
            font=('Times',10,'bold italic')
            )
        #输入框,输入订购数量
        self.entry_input_amount=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )
                 
        #按钮，按下后添加餐品到菜单
        self.button_add=Button(
            master=self,
            text='添加菜品',
            command=self.add_event,
            cursor='plus',
            relief="ridge"
            )  
        
        #按钮，按下后根据ID删除菜品
        self.button_remove=Button(
            master=self,
            text='删除菜品',
            command=self.remove_event,
            cursor='plus',
            relief="ridge"
            )
        
        #文本框，提示输入桌号
        self.label_table=Label(
            master=self,
            text='订购桌号',
            font=('Times',10,'bold italic')
            )
        #输入框,输入桌号
        self.entry_input_table=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )
      
        #按钮，按下后将当前订单写入数据库
        self.button_order=Button(
            master=self,
            text='确认订单',
            command=self.order_event,
            cursor='plus',
            relief="ridge"
            )
        
        self.head_list=['菜品名称',"价格",'数量']
        #当前订购的菜品表格树
        self.treeview_order=ttk.Treeview(
            master=self,
            columns=self.head_list,
            )
        #添加并设置各列
        self.treeview_order.heading('#0',text= "订单编号") 
        self.treeview_order.column('#0',width=60) 
        for head in self.head_list:
            self.treeview_order.heading(column=head,text=head,anchor=CENTER)
            self.treeview_order.column(column=head,width=80,anchor=CENTER)  

        #文本框，显示当前总价
        self.label_price=Label(
            master=self,
            text='当前总价:',
            font=('Times',10,'bold italic'),
        
            )
        self.label_price['anchor']=W
        #文本框，显示预计时间
        self.label_time=Label(
            master=self,
            text='预计时间:',
            font=('Times',10,'bold italic'),
            anchor=S,
            )

        self.grid_all()


                
    def update_treeview(self):
        """更新用户订餐列表"""
         #删除所有菜品结点
        for child in self.treeview_order.get_children():
            self.treeview_order.delete(child)
        for order_dict in self.list_order:
            self.treeview_order.insert('',END,text=order_dict["ID"],value=(order_dict["Name"],order_dict["Price"],order_dict["Amount"]))
        money=0
        time=10
        for order_dict in self.list_order:
            money+=float(order_dict["Price"])*float(order_dict["Amount"])
            time=max(time,float(sqliteTool.get_dish_info(order_dict["Name"],"TIMECOST")))
        
        self.label_price["text"]="当前总价(￥):"+str(money)
        self.label_time["text"]="预计时间(min):"+str(time)

    def add_event(self):
        """根据将菜品添加到订单"""
        if not sqliteTool.get_dish_contain("NAME",self.entry_input_name.get()):
            tkinter.messagebox.showinfo("订餐错误","名为{0}的菜品不在菜单中".format(self.entry_input_name.get()))
            return
        if(len(self.entry_input_name.get())*len(self.entry_input_amount.get())):
            self.dict_order["Name"]=self.entry_input_name.get()
            self.dict_order["Price"]=sqliteTool.get_dish_info(self.dict_order["Name"],"PRICE")
            self.dict_order["Amount"]=self.entry_input_amount.get()
            self.dict_order["ID"]=int(random.uniform(1000, 9999))
            self.list_order.append(self.dict_order.copy())
            self.update_treeview();
            
    def order_event(self):
        """将订单写入数据库"""
        if(len(self.entry_input_table.get())>0):
            for order_dict in self.list_order:
                sqliteTool.add_order(
                    order_dict["ID"],
                    sqliteTool.name2id(order_dict["Name"]),
                    order_dict["Name"],
                    order_dict["Price"],
                    self.entry_input_table.get(),
                    order_dict["Amount"],
                    "已下单",
                    "暂无"
                    )              
                tkinter.messagebox.showinfo("成功下单","餐品{0}的订单号为{1}".format(order_dict["Name"],order_dict["ID"]))
            self.list_order.clear()
            self.update_treeview()

    def remove_event(self):
        """根据输入的序号删除菜品"""
        for order_dict in self.list_order:
            if order_dict["Name"]==self.entry_input_name.get() or order_dict["ID"]==self.entry_input_name.get():
                self.list_order.remove(order_dict)
                self.update_treeview();

    def grid_all(self):
        """布局函数"""
        self.label_name.grid(row=0,column=0)
        self.label_amount.grid(row=0,column=1)       
        self.label_table.grid(row=0,column=2)
        self.button_remove.grid(row=0,column=3,padx='20px',sticky=NS)

        self.entry_input_name.grid(row=1,column=0)
        self.entry_input_amount.grid(row=1,column=1) 
        self.entry_input_table.grid(row=1,column=2)
        self.button_add.grid(row=1,column=3,padx='20px',sticky=NS)
               
        self.treeview_order.grid(row=2,rowspan=4,column=0,columnspan=2,pady='5px',padx='10px')
        self.label_price.grid(row=2,column=2)

        self.label_time.grid(row=3,column=2)
        self.button_order.grid(row=3,column=3,padx='20px',sticky=NS)

class UserViewFrame(Frame):
    """用户展示框架"""
    def __init__(self,master,root=True):
        Frame.__init__(self,master=master) 
        self.root=root;
        #用户类型
        self.user_type=['总管','顾客','管理员','厨师','服务员','采购员']
        
        #人数计数
        self.cook_label=Label(
            master=self,
            text="当前厨师人数:",
            font=('Times',15,'italic')
            )
        self.server_label=Label(
            master=self,
            text="当前服务员人数:",
            font=('Times',15,'italic')
            )
        self.buy_label=Label(
            master=self,
            text="当前采购员人数:",
            font=('Times',15,'italic')
            )

        #用户表格
        self.treeview_user=ttk.Treeview(
            master=self,
            columns=['用户名称','用户密码','身份类型','电话号码','注册时间'],
            )
        #添加并设置各列
        self.treeview_user.heading('#0',text= "用户序号") 
        self.treeview_user.column('#0',width=60) 
        for head in ['用户名称','用户密码','身份类型','电话号码','注册时间']:
            self.treeview_user.heading(column=head,text=head,anchor=CENTER)
            self.treeview_user.column(column=head,width=80,anchor=CENTER)  
        #调用函数添加树结点数据
        self.update_treeview()

        #菜品表格树滚动条
        self.scroll_order=ttk.Scrollbar(
            master=self,
            orient='vertical'
            )
        #双向绑定菜品表格的位置和滚动条位置
        self.treeview_user.configure(yscrollcommand=self.scroll_order.set)
        self.scroll_order.config(command=self.treeview_user.yview)
        
        #刷新用户信息按钮
        self.button_update=Button(
            master=self,
            text='刷新',
            command=self.update_treeview,
            cursor='plus',
            relief="ridge"
            )     

        #调用布局函数
        self.grid_all()

    def update_treeview(self):
        """更新用户订餐列表"""
        list_count=[0,0,0]
        #删除所有用户结点
        for child in self.treeview_user.get_children():
            self.treeview_user.delete(child)
        list_user=sqliteTool.get_user(self.root)
        #插入用户信息
        for user in list_user:
            if user[3]=="厨师":
                list_count[0]+=1
            elif user[3]=="服务员":
                list_count[1]+=1
            elif user[3]=="采购员":
                list_count[2]+=1

            self.treeview_user.insert('',END,text=user[0],value=(user[1],user[2],user[3],user[4],user[5]))
        
        self.cook_label['text']="厨师数:"+str(list_count[0])
        self.server_label['text']="服务员数:"+str(list_count[1])
        self.buy_label['text']="采购员数:"+str(list_count[2])
            
    def grid_all(self):
        """布局函数"""
        self.button_update.grid(row=0,column=0)
        self.cook_label.grid(row=0,column=1)
        self.server_label.grid(row=0,column=2)
        self.buy_label.grid(row=0,column=3)

        self.treeview_user.grid(row=1,column=0,columnspan=4)
        self.scroll_order.grid(row=1,column=4,sticky='SN')

class UpdateUserFrame(Frame):
    """添加用户框架"""
    def __init__(self,master,root=True):
        Frame.__init__(self,master=master)       
        #用户类别
        if root:
            self.list_user_type=['用户类别','顾客','管理员','厨师','服务员','采购员']  
        else:
            self.list_user_type=['用户类别','顾客','厨师','服务员','采购员']  

        #包括信息:['用户名称','用户密码','身份类型','电话号码','注册时间']
        self.label_id=Label(
            master=self,
            text='用户序号',
            font=('Times',10,'bold italic')
            )
        self.entry_input_id=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        self.label_name=Label(
            master=self,
            text='用户名称',
            font=('Times',10,'bold italic')
            )
        self.entry_input_name=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        self.label_password=Label(
            master=self,
            text='用户密码',
            font=('Times',10,'bold italic')
            )
        self.entry_input_password=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )


        #self.label_type=Label(
        #    master=self,
        #    text='菜品类型',
        #    font=('Times',10,'bold italic')
        #    )
        self.combobox_input_type=ttk.Combobox(
            master = self,
            value = self.list_user_type
            )
        self.combobox_input_type.current(0)

        self.label_phone=Label(
            master=self,
            text='用户电话',
            font=('Times',10,'bold italic')
            )

        self.entry_input_phone=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        self.combobox_input_time=ttk.Combobox(
            master = self,
            value = ['是否重置注册时间','重置','不重置']
            )
        self.combobox_input_time.current(0)

                 
        #按钮，按下后根据输入添加菜品
        self.button_add=Button(
            master=self,
            text='添加用户',
            command=self.add_event,
            cursor='plus',
            relief="ridge"
            )     

        self.button_update=Button(
            master=self,
            text='修改信息',
            command=self.update_event,
            cursor='plus',
            relief="ridge"
            )         

        self.button_remove=Button(
            master=self,
            text='删除用户',
            command=self.remove_event,
            cursor='plus',
            relief="ridge"
            )

        self.grid_all()

    def add_event(self):
        """根据输入数据添加用户"""
        sqliteTool.add_user(
            self.entry_input_id.get(),
            self.entry_input_name.get(),
            self.entry_input_password.get(),
            self.combobox_input_type.get(),
            self.entry_input_phone.get(),
            time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                                )                                

    def update_event(self):
        """根据输入的序号修改用户"""
        if self.combobox_input_time.get()=='重置':
            sqliteTool.update_user(
                self.entry_input_id.get(),
                self.entry_input_name.get(),
                self.entry_input_password.get(),
                self.combobox_input_type.get(),
                self.entry_input_phone.get(),
                time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                                )
        else:
            sqliteTool.update_user(
                self.entry_input_id.get(),
                self.entry_input_name.get(),
                self.entry_input_password.get(),
                self.combobox_input_type.get(),
                self.entry_input_phone.get(),
                sqliteTool.get_user_regtime(self.entry_input_id.get())
                                )

    def remove_event(self):
        """根据输入的序号删除用户"""
        sqliteTool.remove_user(self.entry_input_id.get())

    def grid_all(self):
        """布局函数"""      
        self.label_id.grid(row=0,column=0)
        self.button_add.grid(row=0,column=2,rowspan=2,padx='20px',sticky=NS)
              
        self.entry_input_id.grid(row=1,column=0)
        self.combobox_input_type.grid(row=1,column=1,padx='10px')

        self.label_name.grid(row=2,column=0)        
        self.label_password.grid(row=2,column=1)        
        self.button_remove.grid(row=2,column=2,rowspan=2,padx='20px',sticky=NS)

        self.entry_input_name.grid(row=3,column=0)
        self.entry_input_password.grid(row=3,column=1)
       
        self.label_phone.grid(row=4,column=0)
        self.button_update.grid(row=4,column=2,rowspan=2,padx='20px',sticky=NS)

        self.entry_input_phone.grid(row=5,column=0)
        self.combobox_input_time.grid(row=5,column=1,padx='10px')
        
class OrderViewFrame(Frame):
    """订餐展示框架"""
    def __init__(self,master):
        Frame.__init__(self,master=master) 
   
        #人数计数
        self.count_label=Label(
            master=self,
            text="当前订单总数:",
            font=('Times',15,'italic')
            )

        #订单表格
        self.treeview_order=ttk.Treeview(
            master=self,
            columns=['食品编号','食品名称','食品单价','订单桌号','订购数量','订单状态','厨师编号'],
            )
        #添加并设置各列
        self.treeview_order.heading('#0',text= '订单编号') 
        self.treeview_order.column('#0',width=60) 
        for head in ['食品编号','食品名称','食品单价','订单桌号','订购数量','订单状态','厨师编号']:
            self.treeview_order.heading(column=head,text=head,anchor=CENTER)
            self.treeview_order.column(column=head,width=80,anchor=CENTER)  
        #调用函数添加树结点数据
        self.update_treeview()

        #菜品表格树滚动条
        self.scroll_order=ttk.Scrollbar(
            master=self,
            orient='vertical'
            )
        #双向绑定菜品表格的位置和滚动条位置
        self.treeview_order.configure(yscrollcommand=self.scroll_order.set)
        self.scroll_order.config(command=self.treeview_order.yview)

        #刷新用户信息按钮
        self.button_update=Button(
            master=self,
            text='刷新',
            command=self.update_treeview,
            cursor='plus',
            relief="ridge"
            )     

        #调用布局函数
        self.grid_all()

    def update_treeview(self):
        """更新用户订餐列表"""
        #删除所有用户结点
        for child in self.treeview_order.get_children():
            self.treeview_order.delete(child)
        list_order=sqliteTool.get_order()
        self.count_label['text']="当前订单总数:"+str(len(list_order))
        #插入用户信息
        for order in list_order:
            self.treeview_order.insert('',END,text=order[0],value=(order[1],order[2],order[3],order[4],order[5],order[6],order[7]))

    def grid_all(self):
        """布局函数"""
        self.button_update.grid(row=0,column=0)
        self.count_label.grid(row=0,column=1)

        self.treeview_order.grid(row=1,column=0,columnspan=4)
        self.scroll_order.grid(row=1,column=4,sticky='SN')

class CookFrame(Frame):
    """订餐处理框架"""
    def __init__(self,master,cook_id):
        Frame.__init__(self,master=master)    
        #厨师编号
        self.cook_id=cook_id
        #单个订单字典
        self.dict_order={"ID":"","Name":"","Amount":"","Table":""}
        #汇总订单列表
        self.list_order=[]
        
        #文本框，提示输入订单序号
        self.label_id=Label(
            master=self,
            text='订单序号',
            font=('Times',10,'bold italic')
            )
        #输入框,输入订单序号
        self.entry_input_id=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，显示当前接单数
        self.label_count=Label(
            master=self,
            text='当前接单数:',
            font=('Times',10,'bold italic'),
            )
                 
        #按钮，按下后标记订单开始进行
        self.button_add=Button(
            master=self,
            text='接受订单',
            command=self.cook_order,
            cursor='plus',
            relief="ridge"
            )                                
      
        #按钮，按下后标记订单完成
        self.button_fina=Button(
            master=self,
            text='交付订单',
            command=self.fina_order,
            cursor='plus',
            relief="ridge"
            )
        
        self.head_list=['菜品名称','数量','桌号']
        #当前正在处理的订单表格树
        self.treeview_order=ttk.Treeview(
            master=self,
            columns=self.head_list,
            )
        #添加并设置各列
        self.treeview_order.heading('#0',text= "订单编号") 
        self.treeview_order.column('#0',width=60) 
        for head in self.head_list:
            self.treeview_order.heading(column=head,text=head,anchor=CENTER)
            self.treeview_order.column(column=head,width=80,anchor=CENTER)  
        self.update_treeview()        

        self.grid_all()
     
    def cook_order(self):
        """选择订单进行处理"""
        order_id=self.entry_input_id.get()
        order_state=sqliteTool.get_order_info(order_id,"STATE")
        if(order_state=="进行中" or order_state=="已完成"):
            tkinter.messagebox.showinfo("无法接受订单","该订单已经被接受/完成")
        else:
            self.dict_order["ID"]=order_id
            self.dict_order["Name"]=sqliteTool.get_order_info(order_id,"DISHNAME")
            self.dict_order["Amount"]=sqliteTool.get_order_info(order_id,"AMOUNT")
            self.dict_order["Table"]=sqliteTool.get_order_info(order_id,"TABLEID")
            self.list_order.append(self.dict_order.copy())
            sqliteTool.update_order_state(order_id,"进行中",self.cook_id)
            self.update_treeview()
            tkinter.messagebox.showinfo("提示","已接受编号为{0}\n的{1}订单".format(order_id,self.dict_order["Name"]))
            
    
    def fina_order(self):
        """选择订单标识已完成"""
        order_id=self.entry_input_id.get()
        for order_dict in self.list_order:
            if(order_dict["ID"]==order_id):
                sqliteTool.update_order_state(order_id,"已完成",self.cook_id)
                self.list_order.remove(order_dict)
                tkinter.messagebox.showinfo("提示","已完成编号为{0}的订单".format(order_id))
                self.update_treeview()
                return
        tkinter.messagebox.showinfo("无法完成订单","你还没有接受/选择订单")

        
    def update_treeview(self):
        """更新正在处理的订单列表"""
         #删除所有菜品结点
        for child in self.treeview_order.get_children():
            self.treeview_order.delete(child)
        for order_dict in self.list_order:
            self.treeview_order.insert('',END,text=order_dict["ID"],value=(order_dict["Name"],order_dict["Amount"],order_dict["Table"]))
        self.label_count['text']="当前接单数:"+str(len(self.list_order))

    def grid_all(self):
        """布局函数"""
        self.label_id.grid(row=0,column=0)
        self.entry_input_id.grid(row=0,column=1)
        self.treeview_order.grid(row=0,rowspan=4,column=2,columnspan=2,pady='5px',padx='10px')

        self.button_add.grid(row=1,rowspan=1,column=0,padx='10px',sticky=NS)
        self.button_fina.grid(row=1,rowspan=1,column=1,padx='10px',sticky=NS)
                        
        self.label_count.grid(row=2,column=0)
 
class ServerFrame(Frame):
    """订单服务框架"""
    def __init__(self,master,server_id):
        Frame.__init__(self,master=master)    
        #服务员编号
        self.server_id=server_id
        
        #文本框，提示输入订单序号
        self.label_id=Label(
            master=self,
            text='订单序号',
            font=('Times',10,'bold italic')
            )
        #输入框,输入订单序号
        self.entry_input_id=Entry(
            master=self,
            font=('Times',10,'bold italic')
            )

        #文本框，显示当前未送达的订单
        self.label_count=Label(
            master=self,
            text='当前未送达订单:',
            font=('Times',10,'bold italic'),
            )
                                               
        #按钮，按下后标记订单送达
        self.button_fina=Button(
            master=self,
            text='送达订单',
            command=self.fina_order,
            cursor='plus',
            relief="ridge"
            )

        #按钮，按下后标记订单收款
        self.button_gain=Button(
            master=self,
            text='订单收款',
            command=self.gain_order,
            cursor='plus',
            relief="ridge"
            )

        self.head_list=['菜品名称','桌号',"状态"]
        #当前正在处理的订单表格树
        self.treeview_order=ttk.Treeview(
            master=self,
            columns=self.head_list,
            )
        #添加并设置各列
        self.treeview_order.heading('#0',text= "订单编号") 
        self.treeview_order.column('#0',width=60) 
        for head in self.head_list:
            self.treeview_order.heading(column=head,text=head,anchor=CENTER)
            self.treeview_order.column(column=head,width=80,anchor=CENTER)  
        self.update_treeview()        

        self.grid_all()
          
    def fina_order(self):
        """选择订单标识已送达"""
        order_id=self.entry_input_id.get()
        order_state=sqliteTool.get_order_info(order_id,"STATE")
        if order_state=="已送达":
            tkinter.messagebox.showinfo("错误","编号为{0}的订单已被送达".format(order_id))
            return
        if order_state!="已完成":
            tkinter.messagebox.showinfo("错误","编号为{0}的订单还未完成".format(order_id))
            return
        sqliteTool.update_order_state(order_id,"已送达",sqliteTool.get_order_info(order_id,"COOKID"))       
        tkinter.messagebox.showinfo("提示","已送达编号为{0}的订单".format(order_id))
        self.update_treeview()    
        
    def gain_order(self):
        """选择订单标识已收款"""
        order_id=self.entry_input_id.get()
        order_state=sqliteTool.get_order_info(order_id,"STATE")
        if order_state=="已收款":
            tkinter.messagebox.showinfo("错误","编号为{0}的订单已经收款".format(order_id))
            return
        if order_state=="已完成":
            tkinter.messagebox.showinfo("错误","编号为{0}的订单还未配送".format(order_id))
            return
        sqliteTool.update_order_state(order_id,"已收款",sqliteTool.get_order_info(order_id,"COOKID"))  
        price=float(sqliteTool.get_order_info(order_id,"PRICE"))
        amount=float(sqliteTool.get_order_info(order_id,"AMOUNT"))
        money=price*amount
        tkinter.messagebox.showinfo("提示","编号为{0}的订单已经收款{1}".format(order_id,money))
        self.update_treeview()       
        
    def update_treeview(self):
        """更新正在处理的订单列表"""
        for child in self.treeview_order.get_children():
            self.treeview_order.delete(child)
        list_order=sqliteTool.get_order()
        count=0
        for order_dict in list_order:
            if order_dict[6]=="已完成" or order_dict[6]=="已送达":
                count+=1
                self.treeview_order.insert('',END,text=order_dict[0],value=(order_dict[2],order_dict[4],order_dict[6]))
        self.label_count['text']="当前未配送/未收款订单数:"+str(count)

    def grid_all(self):
        """布局函数"""
        self.label_id.grid(row=0,column=0)
        self.entry_input_id.grid(row=0,column=1)
        self.treeview_order.grid(row=0,rowspan=4,column=2,columnspan=2,pady='5px',padx='10px')

        self.button_fina.grid(row=1,rowspan=1,column=0,padx='10px',sticky=NS)
        self.button_gain.grid(row=1,rowspan=1,column=1,padx='10px',sticky=NS)
                        
        self.label_count.grid(row=2,column=0)       
        
class LoginWindow(Tk):
    #生成登录窗口
    def __init__(self):
        Tk.__init__(self)       
        customTool.set_center(self,800,450)
        self.title("餐厅系统登录")

        self.canvas_login_win=Canvas(self,width=800,height=450)
        self.im_login_win=customTool.get_image('background.jpg',800,450)
        self.canvas_login_win.create_image(400,230,image=self.im_login_win)
        self.canvas_login_win.pack()
       

        #添加登录和关闭框架到登录窗口
        self.frame_top=LoginFrame(self)
        self.frame_top.place(x=150,y=100,width=400,height=200)

        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=700,y=400,width=60,height=30)

class DishManagerWindow(Toplevel):
    """管理窗口"""
    def __init__(self):
        Toplevel.__init__(self)       
        customTool.set_center(self,800,450)
        self.title("餐厅管理界面")
        self["background"]="#114514"    
        
        self.frame_top=DishViewFrame(self)
        self.frame_top.place(x=0,y=0,width=800,height=280)
        self.frame_center=AddDishFrame(self)
        self.frame_center.place(x=0,y=280,width=800,height=200)

class UserManagerWindow(Toplevel):
    """管理窗口"""
    def __init__(self,root=True):
        Toplevel.__init__(self)       
        customTool.set_center(self,800,450)
        self.title("用户管理界面")
        self["background"]="#114514"    
        
        self.frame_top=UserViewFrame(self,root)
        self.frame_top.place(x=0,y=0,width=800,height=280)
        self.frame_center=UpdateUserFrame(self,root)
        self.frame_center.place(x=0,y=280,width=800,height=200)

class RegisterWindow(Toplevel):
    #生成登录窗口
    def __init__(self):
        Toplevel.__init__(self)       
        customTool.set_center(self,800,450)
        self.title("餐厅系统注册")

        self.canvas_win=Canvas(self,width=800,height=450)
        self.im_login_win=customTool.get_image('background.jpg',800,450)
        self.canvas_win.create_image(400,230,image=self.im_login_win)
        self.canvas_win.pack()
       

        #添加注册和关闭框架到窗口
        self.frame_top=RegisterFrame(self)
        self.frame_top.place(x=150,y=100,width=400,height=300)

        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=700,y=400,width=60,height=30)

class OrderWindow(Toplevel):
    #生成点餐窗口
    def __init__(self):
        Toplevel.__init__(self)       
        customTool.set_center(self,800,480)
        self.title("用户订餐界面")

        #背景图片
        self.canvas_login_win=Canvas(self,width=800,height=450)
        self.im_login_win=customTool.get_image('background.jpg',800,450)
        self.canvas_login_win.create_image(400,230,image=self.im_login_win)
        self.canvas_login_win.pack()
       

        #添加订餐和关闭框架到登录窗口
        self.frame_top=DishViewFrame(self)
        self.frame_top.place(x=0,y=0,width=800,height=280)
        self.frame_center=OrderDishFrame(self)
        self.frame_center.place(x=0,y=250,width=800,height=200)
        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=700,y=400,width=60,height=30)

class CookWindow(Toplevel):
    #生成厨师订单处理窗口
    def __init__(self,cook_id):
        Toplevel.__init__(self)       
        customTool.set_center(self,800,480)
        self.title("厨师订单处理界面")

        #背景图片
        self.canvas_login_win=Canvas(self,width=800,height=450)
        self.im_login_win=customTool.get_image('background.jpg',800,450)
        self.canvas_login_win.create_image(400,230,image=self.im_login_win)
        self.canvas_login_win.pack()
       
        #添加订单展示和处理框架到登录窗口
        self.frame_top=OrderViewFrame(self)
        self.frame_top.place(x=0,y=0,width=800,height=280)
        
        self.frame_center=CookFrame(self,cook_id)
        self.frame_center.place(x=10,y=300,width=800,height=250)
        
        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=700,y=400,width=60,height=30)

class ServerWindow(Toplevel):
    #生成服务员订单处理窗口
    def __init__(self,user_id):
        Toplevel.__init__(self)       
        customTool.set_center(self,800,480)
        self.title("服务员订单处理界面")

        #背景图片
        self.canvas_login_win=Canvas(self,width=800,height=450)
        self.im_login_win=customTool.get_image('background.jpg',800,450)
        self.canvas_login_win.create_image(400,230,image=self.im_login_win)
        self.canvas_login_win.pack()
       
        #添加订单展示和处理框架到登录窗口
        self.frame_top=OrderViewFrame(self)
        self.frame_top.place(x=0,y=0,width=800,height=280)
        
        self.frame_center=ServerFrame(self,user_id)
        self.frame_center.place(x=10,y=300,width=800,height=250)
        
        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=700,y=400,width=60,height=30)

class OrderViewWindow(Toplevel):
    """订单预览界面"""
    def __init__(self):
        Toplevel.__init__(self)       
        customTool.set_center(self,700,300)
        self.title("订单预览界面")

        #背景图片
        self.canvas_login_win=Canvas(self,width=600,height=300)
        self.im_login_win=customTool.get_image('background.jpg',600,300)
        self.canvas_login_win.create_image(400,230,image=self.im_login_win)
        self.canvas_login_win.pack()
       
        #添加订单展示和处理框架到登录窗口
        self.frame_top=OrderViewFrame(self)
        self.frame_top.place(x=0,y=0,width=650,height=300)
              
        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=560,y=0,width=60,height=30)

class DishViewWindow(Toplevel):
    """餐品预览界面"""
    def __init__(self):
        Toplevel.__init__(self)       
        customTool.set_center(self,600,300)
        self.title("餐品预览界面")

        #背景图片
        self.canvas_login_win=Canvas(self,width=600,height=300)
        self.im_login_win=customTool.get_image('background.jpg',600,300)
        self.canvas_login_win.create_image(400,230,image=self.im_login_win)
        self.canvas_login_win.pack()
       
        #添加订单展示和处理框架到登录窗口
        self.frame_top=DishViewFrame(self)
        self.frame_top.place(x=0,y=0,width=600,height=300)
              
        self.frame_bottom=CloseFrame(self)
        self.frame_bottom.place(x=560,y=0,width=60,height=30)